from apps.common.base.views import *
from apps.common.wx.wxapi import getOpenid
from apps.common.wx.wxapi import getAccessToken
from django.http import FileResponse

class WxViewSet(BaseViewSet):

    '''获取openid'''
    @action(methods=['post'], detail=False, authentication_classes=[], permission_classes=[])
    def getOpenId(self, request):
        params = getRequestParams(request)
        if isEmptyStr(params.get('code')):
            return Response(response_message('code参数必填'))
        if isEmptyStr(params.get('clientname')):
            return Response(response_message('clientname参数必填'))
        data = getOpenid(params.get('code'), params.get('clientname'))
        return Response(response_success({'openid': data.get('openid')}))
    
    '''获取小程序码'''
    @action(methods=['post'], detail=False)
    def getwxacodeunlimit(self, request):
        params = getRequestParams(request)
        res = getAccessToken({'clientname': params.get('clientname')})
        access_token = res["access_token"]
        sendOrder = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + access_token
        headers = {'content-type': "application/json", 'Accept': "application/json",}
        data = {
            "page": "pages/home/home",
            "scene": "a=1",
            "env_version": "release"
        }
        res = requests.post(sendOrder, data=json.dumps(data), headers=headers,)
        image_base64 = str(base64.b64encode(res.content), encoding='utf-8')
        return Response(response_success({'image_base64': image_base64}))
    
    @action(methods=['post'], detail=False)
    def getwxacodeunlimitForBlob(self, request):
        params = getRequestParams(request)
        res = getAccessToken({'clientname': params.get('clientname')})
        access_token = res["access_token"]
        sendOrder = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + access_token
        headers = {'content-type': "application/json", 'Accept': "application/json",}
        data = {
            "page": "pages/home/home",
            "scene": "a=1",
            "env_version": "release"
        }
        res = requests.post(sendOrder, data=json.dumps(data), headers=headers,)
        image_base64 = str(base64.b64encode(res.content), encoding='utf-8')
        return FileResponse(res.content, as_attachment=True, filename='qrcode.png')